package com.ty.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ty.annotation.Auth;
import com.ty.entity.UserEntity;
import com.ty.resp.CommonResp;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author : txy
 * @since : 2024/2/1 14:07
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    /**
     * 请求之前执行的方法，ture放行，否则拦截
     *
     * @param request
     * @param response
     * @param handler  请求方法的对象
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求的控制层方法才拦截 HandlerMethod代表控制层的请求方法
        if (handler instanceof HandlerMethod) {
            String token = request.getHeader("Authorization");
            //给前端返回JSON数据，且是utf-8编码
            response.setContentType("application/json;charset=UTF-8");
            ObjectMapper mapper = new ObjectMapper();
            if (StringUtils.hasText(token)) {//提交了token
                //验证token
                CommonResp result = jwtUtil.parsePayload(token);
                if (result.getSuccess()) {//token有效
                    Object content = result.getContent();
                    Map sysUser = null;

                    if (content instanceof Map) {
                        sysUser = (Map) content;
                        Object o = sysUser.get("userEmail");
                        if (o == null) {
                            sysUser = null;
                        }
                    }
                    String suRole = null; //可能是user admin  user,admin
                    if (sysUser == null) {
                        suRole = "admin";
                    }else {
                        suRole="user";
                    }
                    HandlerMethod method = (HandlerMethod) handler;
                    System.out.println(method);
                    if (method.hasMethodAnnotation(Auth.class)) {//判断方法是否有权限注解
                        Auth auth = method.getMethodAnnotation(Auth.class);
                        String roles = auth.roles();
                        String[] split = roles.split(",");
                        boolean b = false;
                        for (String s : split) {
                            if (suRole.equals(s)) {
                                b = true;
                                break;
                            }
                        }
                        if (!b) {
                            //给前端返回没有访问权限
                            result.setCode(401);
                            result.setSuccess(false);
                            result.setMessage("没有访问权限");
                            String json = mapper.writerFor(CommonResp.class).writeValueAsString(result);
                            PrintWriter writer = response.getWriter();
                            writer.print(json);
                            writer.close();
                            return false;
                        }
                    }
                } else {
                    //无效给前端返回
                    PrintWriter writer = response.getWriter();
                    //result.setMessage("无效token");
                    String json = mapper.writerFor(CommonResp.class).writeValueAsString(result);
                    writer.print(json);
                    writer.close();
                    return false;
                }
            } else {
                //给前端返回没有token
                CommonResp result = new CommonResp();
                result.setCode(401);
                result.setSuccess(false);
                result.setMessage("没有提交token");
                String json = mapper.writerFor(CommonResp.class).writeValueAsString(result);
                PrintWriter writer = response.getWriter();
                writer.print(json);
                writer.close();
                return false;
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

}
